package ui.fragment.homepagefragment;

import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;

import org.angmarch.views.NiceSpinner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import adapter.PracticeAdapter;
import base.BaseBean;
import base.fragment.BaseNetFragment;
import bean.GetSubjectBean;
import bean.PracticeBean;
import student.andlei.com.student.R;
import ui.activity.AnswerSheetActivity;
import ui.activity.DoTheWorkActivity;
import ui.activity.autogenerating_test_paper.IntelligentTestPaperOptionActivity;
import utils.DensityUtil;
import utils.GsonUtils;
import utils.log.LogUtil;

/**
 * 自主练习
 */
public class PracticeFragment extends BaseNetFragment{
    private NiceSpinner spinner_subject,
                        spinner_time;
    private RecyclerView recyclerView;
    private PracticeAdapter adapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private List<PracticeBean.mlist> lists = new ArrayList<>();
    private List<GetSubjectBean> beanList;
    private List<String> allsubjectList = new ArrayList<>();
    private List<String> alltimeList = new ArrayList<>();
    private Button bt_zhineng;
    private int screenWidth,screenHeight;
    private int subject_id = 0;
    private int date;
    private int page = 1;
    public static Fragment getInstance() {
        return new PracticeFragment();
    }
    @Override
    public void success(String action, BaseBean baseBean) {
        hideLoadDialog();
        swipeRefreshLayout.setRefreshing(false);
        adapter.loadMoreEnd();
        if(baseBean.code == 200){
            if(action.equals("schedule/getSubject")){
                beanList  = GsonUtils.getInstance(getActivity()).parseNoHeaderJArray(baseBean, GetSubjectBean.class);
                GetSubjectBean bean0 = new GetSubjectBean();
                bean0.subject_name = "全部科目";
                bean0.subject_id = 0;
                beanList.add(0,bean0);
                for(GetSubjectBean bean:beanList){
                    allsubjectList.add(bean.subject_name);
                }
                spinner_subject.attachDataSource(allsubjectList);
            }else if(action.equals("Task/training")){
                PracticeBean bean = (PracticeBean) GsonUtils.getInstance(context).parseComplexJArrayByCommon(baseBean,PracticeBean.class);
                if(lists == null){
                    lists = new ArrayList<>();
                }
                if(page>bean.page.total_page){
                    LogUtil.app("已是最后一页");
                }else {
                    lists.addAll(bean.list);
                    page++;
                    adapter.setNewData(lists);
                }
            }
        }else {
            toast(baseBean.msg);
        }
    }

    @Override
    public void error(String action, Throwable e) {
        hideLoadDialog();
        swipeRefreshLayout.setRefreshing(false);
        adapter.loadMoreEnd();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_practice;
    }

    @Override
    protected void findViews() {
        swipeRefreshLayout = getView(R.id.swipeRefreshLayout);
        spinner_subject =getView(R.id.spann_select);
        spinner_time = getView(R.id.spann_select_time);
        recyclerView = getView(R.id.rcly_);
        bt_zhineng = getView(R.id.bt_notebook);
    }
    private long clickTime=0;
    @Override
    protected void formatViews() {
        //创建布局管理
        LinearLayoutManager layoutManager = new LinearLayoutManager(this.context);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new PracticeAdapter(R.layout.item_practice, lists);
        recyclerView.setAdapter(adapter);
        adapter.bindToRecyclerView(recyclerView);
        adapter.setEmptyView(R.layout.empty_view);
        ((TextView)(adapter.getEmptyView().findViewById(R.id.tv_empty))).setText("你还没有作业哦");
        //下拉刷新
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                lists.clear();
                page = 1;
                loaddata();
            }
        });
        //上拉加载
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                recyclerView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loaddata();
                    }
                },500);

            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()){
                    case R.id.bt_look_practice:
                        Button button = (Button) view;
                        if(lists.size()<=0){return;}
                        if(button.getText().toString().equals("练习")){
                            Bundle bundle = new Bundle();

                            bundle.putInt("paper_id",lists.get(position).paper_id);
                            bundle.putInt("student_task_id",lists.get(position).student_task_id);
                            bundle.putString("title",lists.get(position).subject_name+"作业");
                            jumpTo(DoTheWorkActivity.class,bundle);
                        }else {
                            Bundle bundle = new Bundle();
                            bundle.putInt("answer_id",lists.get(position).answer_id);
                            bundle.putInt("student_task_id",lists.get(position).student_task_id);
                            jumpTo(AnswerSheetActivity.class,bundle);
                        }

                        break;
                }
            }
        });
        DisplayMetrics dm = getResources().getDisplayMetrics();
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;
        bt_zhineng.setOnTouchListener(new View.OnTouchListener() {
            int lastX, lastY; // 记录移动的最后的位置
            private int btnHeight;

            public boolean onTouch(View v, MotionEvent event) {
                // 获取Action
                int ea = event.getAction();
                switch (ea) {
                    case MotionEvent.ACTION_DOWN: // 按下
                        lastX = (int) event.getRawX();
                        lastY = (int) event.getRawY();
                        clickTime = SystemClock.uptimeMillis();
                        break;
                    case MotionEvent.ACTION_MOVE: // 移动
                        // 移动中动态设置位置
                        int dx = (int) event.getRawX() - lastX;
                        int dy = (int) event.getRawY() - lastY;
                        int left = v.getLeft() + dx;
                        int top = v.getTop() + dy;
                        int right = v.getRight() + dx;
                        int bottom = v.getBottom() + dy;
                        if (left < 0) {
                            left = 0;
                            right = left + v.getWidth();
                        }
                        if (right > screenWidth) {
                            right = screenWidth;
                            left = right - v.getWidth();
                        }
                        if (top < 0) {
                            top = 0;
                            bottom = top + v.getHeight();
                        }
                        if (bottom > (screenHeight- DensityUtil.dp2pxInt(145))) {
                            bottom = (screenHeight- DensityUtil.dp2pxInt(145));
                            top = bottom - v.getHeight();
                        }
                        v.layout(left, top, right, bottom);
                        // Toast.makeText(getActivity(), "position：" + left + ", " +
                        // top + ", " + right + ", " + bottom, 0)
                        // .show();
                        // 将当前的位置再次设置
                        lastX = (int) event.getRawX();
                        lastY = (int) event.getRawY();
                        break;
                    case MotionEvent.ACTION_UP: // 抬起
                        if (SystemClock.uptimeMillis() - clickTime <= 100) {
                            //如果两次的时间差＜1s，就不执行操作
                            jumpTo(IntelligentTestPaperOptionActivity.class);
                        }
                }
                return false;
            }
        });
    }

    @Override
    protected void formatData() {
//        for(int i = 0 ;i<10;i++){
//            PracticeBean.mlist practiceBean = new PracticeBean.mlist();
//            lists.add(practiceBean);
//        }
        //-----时间选择
        alltimeList.add("全部时间");
        alltimeList.add("当天");
        alltimeList.add("本周");
        alltimeList.add("本月");
        spinner_time.attachDataSource(alltimeList);
        //spinner点击
        spinner_time.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                lists.clear();
                page = 1;
                adapter.notifyDataSetChanged();
                date = i;
                loaddata();
                Log.i("PracticeFragment","date----->"+date);
            }
        });
        spinner_subject.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                for(GetSubjectBean bean :beanList){
                    TextView textView = (TextView) view;
                    if(textView.getText().toString().trim().equals(""+bean.subject_name)){
                        subject_id = bean.subject_id;
                    }
                }
                lists.clear();
                page = 1;
                adapter.notifyDataSetChanged();
                loaddata();
                Log.i("PracticeFragment","subject_id----->"+subject_id);
            }
        });
        loaddata();
        post("schedule/getSubject",  GetSubjectBean.class, false);
    }
    private void loaddata(){
        Map<String,String> map = new HashMap<>();
        map.put("subject_id",""+subject_id);
        map.put("date",""+date);
        map.put("page",""+page);
        map.put("page_number","10");
        post("Task/training",map,BaseBean.class,true);
    }
    @Override
    protected void getBundle() {

    }

    @Override
    public void onClick(View view) {

    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            loaddata();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        page = 1;
        lists.clear();
        adapter.notifyDataSetChanged();
        loaddata();
    }
}
